//
//  XFLoginViewController.m
//  
//
//  Created by Kavee DJ on 16/2/20.
//
//

#import "XFLoginViewController.h"
#import <objc/runtime.h>
#import "XFTextfield.h"
#import "MBProgressHUD+Extion.h"
//#import "EMSDK.h"
#import "CommonUtils.h"
#import <AVOSCloud/AVOSCloud.h>

//#import <UMSocialCore/UMSocialCore.h>

@interface XFLoginViewController (){
    NSTimer *counterDownTimer;
    int freezeCounter;
}


@property (weak, nonatomic) IBOutlet UIButton *closeBtn;

@property (weak, nonatomic) IBOutlet UIButton *QQBtn;
@property (weak, nonatomic) IBOutlet UIButton *sinaBtn;
@property (weak, nonatomic) IBOutlet UIButton *tencentBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;
@property (weak, nonatomic) IBOutlet UIView *textView;
@property (weak, nonatomic) IBOutlet UILabel *quickBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftlineWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightlineWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textLeft;

@property (weak, nonatomic) IBOutlet XFTextfield *loginUserNameTextField;
@property (weak, nonatomic) IBOutlet XFTextfield *loginPassWordTextField;
@property (weak, nonatomic) IBOutlet UIButton *clickLoginBtn;

@property (weak, nonatomic) IBOutlet XFTextfield *signInMobileNumTF;
@property (weak, nonatomic) IBOutlet XFTextfield *signInVerifyCodeTF;
@property (weak, nonatomic) IBOutlet UIButton *requestCodeButton;

@end

@implementation XFLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.loginUserNameTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
    [self.loginPassWordTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];

    self.clickLoginBtn.enabled = NO;
    
    self.topConstraint.constant = -250;
    self.leftlineWidth.constant = 0;
    self.rightlineWidth.constant = 0;

    self.forgetBtn.layer.mask = [[CALayer alloc]init];
    self.quickBtn.layer.mask = [[CALayer alloc]init];
    self.registerBtn.layer.mask = [[CALayer alloc]init];
}

- (void)textFieldDidChange {
    NSString *username = self.loginUserNameTextField.text;
    NSString *password = self.loginPassWordTextField.text;
    
    if (username.length == 0 || password.length == 0) {
        self.clickLoginBtn.enabled = NO;
    } else {
        self.clickLoginBtn.enabled = YES;
    }
}

// 点击了登录
- (IBAction)login:(UIButton *)sender {
    NSString *phoneNum = self.loginUserNameTextField.text;
    NSString *password = self.loginPassWordTextField.text;
    
    // 登录
//    EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
//    if (error==nil) {
//        [[EMClient sharedClient].options setIsAutoLogin:YES];
//        [self.view endEditing:YES];
//        [self dismissViewControllerAnimated:YES completion:^{
//            KLog(@"通知外界,换头像,换昵称,换background")
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"SuccessLogin" object:nil];
//        }];
//        
//    }else{
//        [MBProgressHUD showError:@"用户名或密码错误"];
//    }
    
    [AVUser logInWithMobilePhoneNumberInBackground:phoneNum password:password block:^(AVUser * _Nullable user, NSError * _Nullable error) {
        if (error) {
            [MBProgressHUD showError:@"用户名或密码错误"];
        } else {
            [self.view endEditing:YES];
            [self dismissViewControllerAnimated:YES completion:^{
                KLog(@"通知外界,换头像,换昵称,换background")
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SuccessLogin" object:nil];
            }];
        }
    }];
}

// 点击了获取验证码
- (IBAction)requestVerifyCode:(UIButton *)sender {
    NSString *mobileNum = self.signInMobileNumTF.text;
    // 判断手机号是否争取
    if (mobileNum.length != 11) {
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"手机号码无效。" forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"LeanSMSDemo" code:1024 userInfo:details];
        [CommonUtils displayError:error];
        return;
    }
    

    
    // 正确，且未登录
    [AVOSCloud requestSmsCodeWithPhoneNumber:mobileNum callback:^(BOOL succeeded, NSError * _Nullable error) {
        if (error) {
            [CommonUtils displayError:error];
        } else {
            [self freezeMoreRequest];
        }
    }];
}

- (void)freezeMoreRequest {
    // 一分钟内禁止再次发送
    [self.requestCodeButton setEnabled:NO];
    freezeCounter = 60;
    counterDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownRequestTimer) userInfo:nil repeats:YES];
    [counterDownTimer fire];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"验证码已发送" message:@"验证码已发送到你请求的手机号码。如果没有收到，可以在一分钟后尝试重新发送。"
                                                       delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)countDownRequestTimer {
    static NSString *counterFormat = @"%d";
    --freezeCounter;
    if (freezeCounter<= 0) {
        [counterDownTimer invalidate];
        counterDownTimer = nil;
        [self.requestCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.requestCodeButton setEnabled:YES];
    } else {
        [self.requestCodeButton setTitle:[NSString stringWithFormat:counterFormat, freezeCounter] forState:UIControlStateNormal];
    }
}

// 点击了注册
- (IBAction)signIn:(UIButton *)sender {
    NSString *mobileNum = self.signInMobileNumTF.text;
    NSString *smsCode = self.signInVerifyCodeTF.text;
    if (mobileNum.length != 11) {
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"手机号码无效。" forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"LeanSMSDemo" code:1024 userInfo:details];
        [CommonUtils displayError:error];
        return;
    }
    if (smsCode.length < 6) {
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"验证码无效。" forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"LeanSMSDemo" code:1024 userInfo:details];
        [CommonUtils displayError:error];
        return;
    }
    // 注册，或者是直接登录
    [AVUser signUpOrLoginWithMobilePhoneNumberInBackground:mobileNum smsCode:smsCode block:^(AVUser * _Nullable user, NSError * _Nullable error) {
        if (error) {
            [CommonUtils displayError:error];
        } else {
//            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"用户登录成功！" delegate:nil
//                                                      cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//            [alertView show];
            [self.view endEditing:YES];
            [self dismissViewControllerAnimated:YES completion:^{
                KLog(@"通知外界,换头像,换昵称,换background")
                [[NSNotificationCenter defaultCenter] postNotificationName:@"SuccessLogin" object:nil];
            }];
        }
    }];
    
}

//注册按钮
- (IBAction)registerBtn:(UIButton *)sender {
    if (self.textLeft.constant == 0) { // 显示注册界面
        self.textLeft.constant = - self.view.kdj_width;
        sender.selected = YES;
    } else { // 显示登录界面
        self.textLeft.constant = 0;
        sender.selected = NO;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];

}
//需要的动画
-(void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    [UIView animateWithDuration:1.0 animations:^{
        self.closeBtn.transform = CGAffineTransformMakeRotation(M_PI);
        
    }];
    
    self.topConstraint.constant = 40;
    self.leftlineWidth.constant = 103;
    self.rightlineWidth.constant = 103;

    [UIView animateWithDuration:1.0 delay:0.5 usingSpringWithDamping:0.3 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        //忘记密码动画
        [self setupAnimationWithStartRect:CGRectMake(0, 0, 0, CGRectGetHeight(self.forgetBtn.frame)) endRect:CGRectMake(0, 0, CGRectGetWidth(self.forgetBtn.frame), CGRectGetHeight(self.forgetBtn.frame)) object:self.forgetBtn duration:0.5];
        //注册按钮动画
        [self setupAnimationWithStartRect:CGRectMake(-(CGRectGetWidth(self.registerBtn.frame)), 0, 0, CGRectGetHeight(self.registerBtn.frame)) endRect:CGRectMake(0, 0, CGRectGetWidth(self.registerBtn.frame), CGRectGetHeight(self.registerBtn.frame)) object:self.registerBtn duration:0.5];
        
    }];
    
    //快速登录动画
    [self setupAnimationWithStartRect:CGRectMake(self.quickBtn.kdj_width/2, 0, 0, CGRectGetHeight(self.quickBtn.frame)) endRect:CGRectMake(0, 0, CGRectGetWidth(self.quickBtn.frame), CGRectGetHeight(self.quickBtn.frame)) object:self.quickBtn duration:0.5];
    
    
    [UIView animateWithDuration:0.1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:10 options:UIViewAnimationOptionCurveLinear animations:^{
        self.QQBtn.transform = CGAffineTransformMakeScale(0.01, 0.01);
        self.sinaBtn.transform = CGAffineTransformMakeScale(0.01, 0.01);
        self.tencentBtn.transform = CGAffineTransformMakeScale(0.01, 0.01);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:1 delay:1.5 usingSpringWithDamping:0.4 initialSpringVelocity:10 options:UIViewAnimationOptionCurveLinear animations:^{
                    self.QQBtn.transform = CGAffineTransformIdentity;
                    self.sinaBtn.transform = CGAffineTransformIdentity;
                    self.tencentBtn.transform = CGAffineTransformIdentity;

                } completion:nil];
        }];
    
}


//设置动画
-(void)setupAnimationWithStartRect:(CGRect)startRect endRect:(CGRect)endRect object:(UIView *)view duration:(NSTimeInterval)duration {
    
    UIBezierPath *beginPath = [UIBezierPath bezierPathWithRect:startRect];
    
    UIBezierPath *endPath = [UIBezierPath bezierPathWithRect:endRect];
    
    CAShapeLayer *quickMask = [[CAShapeLayer alloc]init];
    quickMask.path = endPath.CGPath;
    quickMask.fillColor = [UIColor whiteColor].CGColor;
    view.layer.mask = quickMask;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"path"] ;
    animation.duration = duration;
    animation.beginTime = CACurrentMediaTime();
    animation.fromValue = (__bridge id _Nullable)(beginPath.CGPath);
    animation.toValue = (__bridge id _Nullable)(endPath.CGPath);
    [quickMask addAnimation:animation forKey:@"path"];

}

//- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
//{
//    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
//        UMSocialUserInfoResponse *userinfo =result;
//        NSString *message = [NSString stringWithFormat:@"name: %@\n icon: %@\n gender: %@\n",userinfo.name,userinfo.iconurl,userinfo.gender];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"UserInfo"
//                                                        message:message
//                                                       delegate:nil
//                                              cancelButtonTitle:NSLocalizedString(@"确定", nil)
//                                              otherButtonTitles:nil];
//        [alert show];
//    }];
//    
//}


#pragma mark - 第三方登录
- (IBAction)sinaBtnClick {
//    [self getUserInfoForPlatform:UMSocialPlatformType_Sina];
    // 取消授权
//    [[UMSocialManager defaultManager] cancelAuthWithPlatform:UMSocialPlatformType_Sina completion:^(id result, NSError *error) {
//        NSLog(@"%@,%@",result,error);
//    }];
    KLog(@"点击了新浪微博登录")
    NSString *title = @"新浪微博";
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ThirdLogin" object:title];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)qqBtnClick {
//    [self getUserInfoForPlatform:UMSocialPlatformType_QQ];
    KLog(@"点击了QQ登录")
    NSString *title = @"QQ";
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ThirdLogin" object:title];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)txWbClick {
//    [self getUserInfoForPlatform:UMS//ocialPlatformType_TencentWb];
    KLog(@"点击了微信登录")
    NSString *title = @"微信";
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ThirdLogin" object:title];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//关闭控制器
- (IBAction)close:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(UIStatusBarStyle)preferredStatusBarStyle {
    return  UIStatusBarStyleLightContent;
}

@end
